<template>
  <div class="agent-container">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">智能体管理</h2>
        <p class="page-subtitle">管理您的AI智能体，创建个性化助手</p>
      </div>
      <div class="action-bar">
        <el-button type="primary" @click="handleCreateAgent" :icon="Plus" class="create-btn">
          创建智能体
        </el-button>
        <el-input
          v-model="searchObject.name"
          placeholder="搜索智能体"
          class="search-input"
          clearable
          @clear="search"
          @keyup.enter="search"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 智能体列表 -->
    <el-skeleton :loading="loading" animated :count="4" class="skeleton-list" v-if="loading">
      <template #template>
        <div class="skeleton-card">
          <div class="skeleton-header">
            <el-skeleton-item variant="circle" style="width: 50px; height: 50px;" />
            <div class="skeleton-content">
              <el-skeleton-item variant="text" style="width: 50%" />
              <el-skeleton-item variant="text" style="width: 80%" />
            </div>
          </div>
          <div class="skeleton-footer">
            <el-skeleton-item variant="button" style="width: 60px; margin-right: 10px;" />
            <el-skeleton-item variant="button" style="width: 60px" />
          </div>
        </div>
      </template>
    </el-skeleton>

    <el-empty description="暂无智能体" v-if="!loading && (!pageData.data || pageData.data.length === 0)">
      <el-button type="primary" @click="handleCreateAgent">创建智能体</el-button>
    </el-empty>

    <div class="agent-list" v-if="!loading && pageData.data && pageData.data.length > 0">
      <el-card
        v-for="agent in pageData.data"
        :key="agent.id"
        class="agent-card"
        :body-style="{ padding: '0' }"
        @click="handleChatWithAgent(agent)"
      >
        <div class="card-content">
          <div class="agent-info">
            <el-avatar :src="agent.avatar" :size="60" class="agent-avatar">
              {{ agent.name.charAt(0).toUpperCase() }}
            </el-avatar>
            <div class="agent-details">
              <h3 class="agent-name">{{ agent.name }}</h3>
              <p class="agent-description">{{ agent.description }}</p>
            </div>
          </div>
          <div class="agent-status">
            <el-tag size="small" type="success" effect="light">在线</el-tag>
          </div>
          <div class="agent-actions" @click.stop>
            <el-tooltip content="编辑智能体" placement="top" :show-after="300">
              <el-button type="primary" text circle @click="handleEdit(agent)">
                <el-icon><Edit /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除智能体" placement="top" :show-after="300">
              <el-button type="danger" text circle @click="handleDelete(agent)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
        <div class="card-footer">
          <el-button type="primary" text class="chat-btn">
            <el-icon><ChatDotRound /></el-icon> 开始对话
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 分页器 -->
    <div class="pagination-container" v-if="!loading && pageData.data && pageData.data.length > 0">
      <el-pagination
        background
        :current-page="searchObject.no"
        :page-sizes="[8, 16, 40, 80]"
        :page-size="pageData.size"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :page-count="pageData.totalPage"
        :total="pageData.total"
        @size-change="sizeChange"
        @current-change="pageChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus, Search, Edit, Delete, ChatDotRound } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from "vue-router";
import {defineStore} from "pinia";
import {usePage} from "@/utils/usePage.js";
import {useDelete} from "@/utils/useDeleteConfirm.js";
import {useView} from "@/utils/useView.js";
const router = useRouter();

// 标签页控制
const activeTab = ref('agents')

// 智能体列表数据
const agentList = ref([])

// 智能体集合列表数据
const collectionList = ref([])

// 对话框控制
const dialogTitle = ref('创建智能体')

// 集合对话框控制
const collectionDialogVisible = ref(false)
const collectionDialogTitle = ref('创建智能体集合')

// 表单数据
const agentForm = reactive({
  id: '',
  name: '',
  description: '',
  avatar: '',
  systemPrompt: ''
})

// 集合表单数据
const collectionForm = reactive({
  id: '',
  name: '',
  description: '',
  avatar: '',
  selectedAgents: []
})

// 可选智能体列表
const availableAgents = computed(() => {
  return agentList.value.map(agent => ({
    id: agent.id,
    name: agent.name
  }))
})

// 重置表单
const resetForm = () => {
  agentForm.id = ''
  agentForm.name = ''
  agentForm.description = ''
  agentForm.avatar = ''
  agentForm.systemPrompt = ''
}

// 重置集合表单
const resetCollectionForm = () => {
  collectionForm.id = ''
  collectionForm.name = ''
  collectionForm.description = ''
  collectionForm.avatar = ''
  collectionForm.selectedAgents = []
}

// 创建智能体
const handleCreateAgent = () => {
  router.push(`/chat/agent/config`)
}

// 创建智能体集合
const handleCreateCollection = () => {
  resetCollectionForm()
  collectionDialogTitle.value = '创建智能体集合'
  collectionDialogVisible.value = true
}

// 编辑智能体
const handleEdit = (agent) => {
  router.push(`/chat/agent/config?id=${agent.id}`)
}

// 与智能体聊天
const handleChatWithAgent = (agent) => {
  router.push(`/chat/agent/chat?id=${agent.id}`)
}

// 编辑智能体集合
const handleEditCollection = (collection) => {
  collectionDialogTitle.value = '编辑智能体集合'
  collectionForm.id = collection.id
  collectionForm.name = collection.name
  collectionForm.description = collection.description
  collectionForm.avatar = collection.avatar
  collectionForm.selectedAgents = collection.agents ? collection.agents.map(agent => agent.id) : []
  collectionDialogVisible.value = true
}

// 删除智能体

// 删除智能体集合
const handleDeleteCollection = async (collection) => {
  try {
    await ElMessageBox.confirm('确认删除该智能体集合吗？', '提示', {
      type: 'warning'
    })
    // TODO: 调用删除集合API
    ElMessage.success('删除成功')
    // 重新获取列表
    fetchCollectionList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 头像上传成功回调
const handleAvatarSuccess = (response) => {
  agentForm.avatar = response.url
}

// 集合头像上传成功回调
const handleCollectionAvatarSuccess = (response) => {
  collectionForm.avatar = response.url
}

// 提交表单
const handleSubmit = async () => {
  try {
    // TODO: 调用创建/更新API
    const isEdit = !!agentForm.id
    // const response = await (isEdit ? updateAgent(agentForm) : createAgent(agentForm))

    ElMessage.success(isEdit ? '更新成功' : '创建成功')
    dialogVisible.value = false
    // 重新获取列表
    fetchAgentList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

// 提交集合表单
const handleCollectionSubmit = async () => {
  try {
    // TODO: 调用创建/更新集合API
    const isEdit = !!collectionForm.id
    // const response = await (isEdit ? updateCollection(collectionForm) : createCollection(collectionForm))

    ElMessage.success(isEdit ? '更新成功' : '创建成功')
    collectionDialogVisible.value = false
    // 重新获取列表
    fetchCollectionList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

// 获取智能体列表
const fetchAgentList = async () => {
  try {
    // TODO: 调用获取列表API
    // const response = await getAgentList()
    // agentList.value = response.data

    // 模拟数据
    agentList.value = [
      {
        id: '1',
        name: '客服助手',
        description: '专业解答客户问题的智能助手',
        avatar: ''
      },
      {
        id: '2',
        name: '营销专家',
        description: '帮助制定营销策略的智能体',
        avatar: ''
      },
      {
        id: '3',
        name: '数据分析师',
        description: '专注于数据分析和可视化的智能体',
        avatar: ''
      },
      {
        id: '4',
        name: '内容创作者',
        description: '帮助创作高质量内容的智能体',
        avatar: ''
      },
      {
        id: '5',
        name: '技术支持',
        description: '提供技术问题解答和故障排除的智能体',
        avatar: ''
      },
      {
        id: '6',
        name: '产品顾问',
        description: '提供产品咨询和推荐的智能体',
        avatar: ''
      }
    ]
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  }
}

// 获取智能体集合列表
const fetchCollectionList = async () => {
  try {
    // TODO: 调用获取集合列表API
    // const response = await getCollectionList()
    // collectionList.value = response.data

    // 模拟数据
    collectionList.value = [
      {
        id: '1',
        name: '客户服务团队',
        description: '处理客户服务相关的智能体集合',
        avatar: '',
        agents: [
          {
            id: '1',
            name: '客服助手',
            avatar: ''
          },
          {
            id: '2',
            name: '营销专家',
            avatar: ''
          },
          {
            id: '5',
            name: '技术支持',
            avatar: ''
          }
        ]
      },
      {
        id: '2',
        name: '内容创作团队',
        description: '负责内容创作和数据分析的智能体集合',
        avatar: '',
        agents: [
          {
            id: '3',
            name: '数据分析师',
            avatar: ''
          },
          {
            id: '4',
            name: '内容创作者',
            avatar: ''
          }
        ]
      },
      {
        id: '3',
        name: '产品开发团队',
        description: '负责产品开发和技术支持的智能体集合',
        avatar: '',
        agents: [
          {
            id: '5',
            name: '技术支持',
            avatar: ''
          },
          {
            id: '6',
            name: '产品顾问',
            avatar: ''
          }
        ]
      },
      {
        id: '4',
        name: '全能团队',
        description: '包含所有智能体的综合集合',
        avatar: '',
        agents: [
          {
            id: '1',
            name: '客服助手',
            avatar: ''
          },
          {
            id: '2',
            name: '营销专家',
            avatar: ''
          },
          {
            id: '3',
            name: '数据分析师',
            avatar: ''
          },
          {
            id: '4',
            name: '内容创作者',
            avatar: ''
          },
          {
            id: '5',
            name: '技术支持',
            avatar: ''
          },
          {
            id: '6',
            name: '产品顾问',
            avatar: ''
          }
        ]
      }
    ]
  } catch (error) {
    console.error('获取集合列表失败:', error)
    ElMessage.error('获取集合列表失败')
  }
}

// 初始化
const searchForm = ref()
const searchStore = defineStore('queryTemplateStore', {

  state: () => {
    return {
      searchObject: {
        no: 1,
        size: 30,
        sortField: "addDate",
        sortMethod: "desc",
        name: null,
        id:null,
        queryCatalog: null,
        type: null
      }
    }
  }
})

const {searchObject} = searchStore();

const clearSearch = () => {
  searchObject.id=null;
  searchObject.name=null;
  search();
}
const {
  pageData,
  sizeChange,
  pageChange,
  search,
  changeTableSort,
  loading
} = usePage("/agent/search", searchObject);

const {handleDelete} = useDelete("/agent/delete",search);

const {showView, addView, editView} = useView();

// 页面加载时自动搜索
onMounted(() => {
  search();
});
</script>

<style scoped>
.agent-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 页面标题和操作栏 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 8px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.action-bar {
  display: flex;
  gap: 16px;
  align-items: center;
}

.create-btn {
  font-weight: 500;
  padding: 10px 20px;
}

.search-input {
  width: 240px;
}

/* 骨架屏 */
.skeleton-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.skeleton-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.skeleton-header {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.skeleton-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.skeleton-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 智能体列表 */
.agent-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.agent-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;
}

.agent-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  border-color: var(--el-color-primary-light-5);
}

.card-content {
  padding: 20px;
  position: relative;
}

.agent-info {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 16px;
}

.agent-avatar {
  background: linear-gradient(135deg, var(--el-color-primary-light-7), var(--el-color-primary));
  color: #fff;
  font-weight: bold;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.agent-details {
  flex: 1;
}

.agent-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.agent-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5;
}

.agent-status {
  position: absolute;
  top: 20px;
  right: 20px;
}

.agent-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 16px;
}

.card-footer {
  background-color: #f5f7fa;
  padding: 12px 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #ebeef5;
}

.chat-btn {
  width: 100%;
  justify-content: center;
  font-weight: 500;
}

.chat-btn .el-icon {
  margin-right: 4px;
}

/* 分页器 */
.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .action-bar {
    margin-top: 16px;
    width: 100%;
  }
  
  .search-input {
    width: 100%;
  }
  
  .agent-list {
    grid-template-columns: 1fr;
  }
}
</style>
